// Copyright 2007 the original author or authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package lichen.internal.job;

import java.util.Date;

import lichen.entities.user.OnlineUser;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

/**
 * 检查在线用户的job.
 * <p>供Quartz调用.
 * @author jcai
 * @version $Revision: 138 $
 * @since 0.0.1
 */
public class CheckOnline implements Job{
	/**
	 * Logger for this class
	 */
	private static final Log logger = LogFactory.getLog(CheckOnline.class);

	
	private static final long MAX_ONLINE_TIME=20*60*1000;
	/**
	 * 
	 * @see org.quartz.Job#execute(org.quartz.JobExecutionContext)
	 */
	public void execute(JobExecutionContext context) throws JobExecutionException {
		SessionFactory sessionFactory=(SessionFactory) context.getJobDetail().getJobDataMap().get(SchedulerJobModule.HIBERNATE_SESSION_SOURCE);
		Session session = sessionFactory.openSession();
		Transaction transaction = null;
		try{
			transaction = session.beginTransaction();
			Date date= new Date();
			long time=date.getTime();
			Query q = session.getNamedQuery(OnlineUser.DELETE_TIMEOUT_USERS_QUERY);
			q.setLong(0, time-MAX_ONLINE_TIME);
			int rows=q.executeUpdate();
			if (logger.isDebugEnabled()) {
				logger.debug("delete online users ["+rows+"]"); //$NON-NLS-1$
			}
			transaction.commit();
		}catch(Exception e){
			e.printStackTrace();
			transaction.rollback();
		}
		finally{
			if(session.isConnected()){
				session.close();
			}
		}
	}
}
